let that
let request = require('../../operation/operation.js')
let bxt = require('../../utils/bxt.js')
let userModel = require('../../models/user.js')
let email
let notice
let klassSid
let util = require('../../utils/util.js')

function init(source,tmpNotice) {
  that = source, notice = tmpNotice
  let emailDesc = '' 
  if (notice.receiptRequirement == 'text' || notice.receiptRequirement == 'image') {
      emailDesc = '【通知签收情况】将以邮件形式发送到您的邮箱。'
      if (notice.receiptRequirement == 'text') {
        emailDesc = emailDesc + '邮件中点击Excel文件下载地址，'
      } else {
        emailDesc = emailDesc + '邮件中点击Excel文件或者图片压缩包下载地址，'
      }

      emailDesc = emailDesc + '可查看完整的签收信息。'
  }

  that.setData({
    emailDesc: emailDesc
  })
}

function setEmail(value) {
  email = value
  if (email) {
    that.setData({
      email: email
    })
  }
}

function show(tmpKlassSid) {
  klassSid = tmpKlassSid
  email = userModel.getUserEmail()
  if (email) {
    that.setData({
      email: email
    })
  }
  
  let dialogComponent = that.selectComponent('.wxc-dialog')
  dialogComponent && dialogComponent.show();
}

function cancel() {
  let dialogComponent = that.selectComponent('.wxc-dialog')
  dialogComponent && dialogComponent.hide();
}

function confirm() {
  if (util.checkEmailFormat(email.trim())) {
    cancel()
    userModel.setUserEmail(email.trim())
    exportEmail()
  } else {
    wx.showToast({
      title: '邮箱格式不正确',
      icon: 'none',
    })
  }
}

/**
  * 通知服务器发送通知签收结果邮件
  * @param email
  */
function exportEmail() {
  wx.showLoading({
    title: '请稍候',
    mask: true
  })
  var param = { 'email': email.trim(), 'noticeSid': notice.sid, 'klassSid': klassSid }
  request.postRequest('/export', param, true)
    .then(res => {
      wx.hideLoading()
      var data = res.data;
      if (request.SUCCESSED == data.status) {
        wx.navigateTo({
          url: '../msgSuccess/msgSuccess?title=' + data.msg + '&desc=' + data.extra + '。（如果邮件不在邮箱的【收件箱】中，请查看邮箱的【垃圾箱】中是否有此邮件。）'
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
        })
      }

    }).catch(e => {
      wx.hideLoading()
      console.log(e)
    })
}

module.exports = {
  init: init,
  cancel: cancel,
  show: show,
  confirm: confirm,
  setEmail: setEmail
}